package com.mszlu.blog.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mszlu.blog.dao.mapper.ArticleBodyMapper;
import com.mszlu.blog.dao.mapper.ArticleMapper;
import com.mszlu.blog.dao.mapper.ArticleTagMapper;
import com.mszlu.blog.dao.pojo.Article;
import com.mszlu.blog.dao.dos.Archives;
import com.mszlu.blog.dao.pojo.ArticleBody;
import com.mszlu.blog.dao.pojo.ArticleTag;
import com.mszlu.blog.dao.pojo.SysUser;
import com.mszlu.blog.service.*;
import com.mszlu.blog.utils.UserThreadLocal;
import com.mszlu.blog.vo.ArticleBodyVo;
import com.mszlu.blog.vo.ArticleVo;
import com.mszlu.blog.vo.Result;
import com.mszlu.blog.vo.TagVo;
import com.mszlu.blog.vo.params.ArticleParam;
import com.mszlu.blog.vo.params.PageParams;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@Service
public class ArticleServiceImpl implements ArticleService {
    @Autowired
    private ArticleMapper articleMapper;
    @Autowired
    private TagService tagService;
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private ArticleTagMapper articleTagMapper;

    @Override
    public Result listArticle(PageParams pageParams) {
        Page<Article> page = new Page<>(pageParams.getPage(), pageParams.getPageSize());
        IPage<Article> articleIPage = articleMapper.listArticle(
                page,
                pageParams.getCategoryId(),
                pageParams.getTagId(),
                pageParams.getYear(),
                pageParams.getMonth());
        List<Article> records = articleIPage.getRecords();
        return Result.success(copyList(records,true,true));

    }

//    @Override
//    public Result listArticle(PageParams pageParams) {
//        /**
//         * 1.分页查询： Article数据库表
//         * page对象里面传入了 当前页数和页面大小
//         * queryWrapper对象，先进行置顶排序，然后按照创建时间进行排序。
//         */
//        Page<Article> page = new Page<>(pageParams.getPage(), pageParams.getPageSize());
//        LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper<>();
//        if(pageParams.getCategoryId()!=null){
//            queryWrapper.eq(Article::getCategoryId,pageParams.getCategoryId());//显示和前端传递的文章分类一样的文章
//        }
//
//        List<Long> articleIdList=new ArrayList<>();
//        if(pageParams.getTagId()!=null){
//            //条件查询： 根据标签来查询对应 的文章
//            //article表并没有tag字段。 因为一篇文章可能有多个标签。
//            //article_tag表 里面有article_id和tag_id对应的关系【1对多，一篇文章多个标签】
//            LambdaQueryWrapper<ArticleTag> articleTagLambdaQueryWrapper=new LambdaQueryWrapper<>();
//            articleTagLambdaQueryWrapper.eq(ArticleTag::getTagId,pageParams.getTagId()); //根据前端传入标签id，来查询符合条件的所有标签
//            List<ArticleTag> articleTags = articleTagMapper.selectList(articleTagLambdaQueryWrapper);
//            for (ArticleTag articleTag : articleTags) {
//                articleIdList.add(articleTag.getArticleId());//将标签id对应的文章id存入articleIdList
//            }
//            if (articleIdList.size()>0){
//                //and id in(1,9,10);   标签id 7---》springmvc,所对应的文章id有 1， 9，10
//                queryWrapper.in(Article::getId,articleIdList);
//            }
//        }
//        //1.是否置顶进行排序。
//        queryWrapper.orderByDesc(Article::getWeight);
//        //2.然后根据创建时间，进行排序。order by create_date desc
//        queryWrapper.orderByDesc(Article::getCreateDate);  //倒序排列：从大到小
//        Page<Article> articlePage = articleMapper.selectPage(page, queryWrapper);//MP的分页查询
//        List<Article> records = articlePage.getRecords();
//        //这个 List<Article> 能直接返回吗？ 很明显不能。 Article是数据库的数据，而我们实际上页面展示的数据，不一定是数据库正常展示的数据。
//        List<ArticleVo> articleVoList = copyList(records, true, true); //将List<Article> 转换成对应的 Vo对象。
//
//        return Result.success(articleVoList);
//    }

    @Override
    public Result hotArticle(int limit) {

        //select id,title from article order by view_counts desc limt 5
        LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByDesc(Article::getViewCounts);
        queryWrapper.select(Article::getId, Article::getTitle);
        queryWrapper.last("limit " + limit); //limit后面记得带空格，不然加载失败。
        List<Article> articles = articleMapper.selectList(queryWrapper);
        //返回vo对象
        return Result.success(copyList(articles, false, false));
    }

    @Override
    public Result newArticle(int limit) {

        LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByDesc(Article::getCreateDate);
        queryWrapper.select(Article::getId, Article::getTitle);
        queryWrapper.last("limit " + limit); // last() 在SQL语句最后面加上
        List<Article> articles = articleMapper.selectList(queryWrapper);
        return Result.success(copyList(articles, false, false));
    }

    @Override
    public Result listArchives() {
        List<Archives> archivesList = articleMapper.listArchives();
        return Result.success(archivesList);
    }

    @Autowired
    private ThreadService threadService;

    @Override
    public Result findArticleById(Long articleId) {
        /**
         * 1. 根据id查询 文章信息
         * 2. 根据bodyId和categoryid 去做关联查询
         */
        Article article = this.articleMapper.selectById(articleId);
        //数据库中的List<Article>转换为List<ArticleVo>,因为前端Vue的data格式是ArticleVo。
        ArticleVo articleVo = copy(article, true, true,true,true);
        //查看完文章了，新增阅读数，有没有问题呢？
        //查看完文章之后，本应该直接返回数据了，这时候做了一个更新操作，更新时会自动加写锁，阻塞其他的读操作，性能就会比较低
        // 更新 增加了此次接口的 耗时 如果一旦更新出问题，不能影响 查看文章的操作
        //线程池  可以把更新操作 扔到线程池中去执行，和主线程就不相关了
        threadService.updateArticleViewCount(articleMapper,article);
        return Result.success(articleVo);
    }

    @Override
    public Result publish(ArticleParam articleParam) {
        //先登录才能拿到用户的数据。将我们的文章发表加入到拦截器
        SysUser sysUser = UserThreadLocal.get();
        /**
         * 1. 发布文章 需要 构建Article对象,然后填充到数据库
         * 2. 作者id  当前的登录用户
         * 3. 标签tag  要将标签加入到 关联列表当中。article_tag表和article表关联
         * 4. body 内容存储 article bodyId
         */
        Article article = new Article();
        article.setAuthorId(sysUser.getId());
        article.setWeight(Article.Article_Common);
        article.setViewCounts(0);
        article.setTitle(articleParam.getTitle());
        article.setSummary(articleParam.getSummary());
        article.setCommentCounts(0);
        article.setCreateDate(System.currentTimeMillis());
        article.setCategoryId(articleParam.getCategory().getId());
        //3.插入之后会生成文章ID,这个时候就能article.getId()了
        articleMapper.insert(article);
        //tag.
        List<TagVo> tags = articleParam.getTags();
        if (tags!=null){
            //对于前端传递过来的参数articleParam的标签进行遍历赋值
            for (TagVo tag : tags) {
                Long articleId = article.getId();//文章ID
                ArticleTag articleTag = new ArticleTag();
                articleTag.setTagId(tag.getId());//设置article_tag表的tag_id
                articleTag.setArticleId(articleId);//通过ms_article表的id来赋值 “article_tag”表的 article_id
                articleTagMapper.insert(articleTag);
            }
        }
        //body。 ms_article_body 和 ms_article_body关联
        ArticleBody articleBody = new ArticleBody();
        articleBody.setArticleId(article.getId());
        articleBody.setContent(articleParam.getBody().getContent());
        articleBody.setContentHtml(articleParam.getBody().getContentHtml());
        articleBodyMapper.insert(articleBody); //插入之后自动生成ms_article_body表的id

        article.setBodyId(articleBody.getId());
        articleMapper.updateById(article);//将我们的body_id更新到ms_article表
        HashMap<String, String> map = new HashMap<>();
        map.put("id",article.getId().toString());
        return Result.success(map);
    }

    private List<ArticleVo> copyList(List<Article> records, boolean isTag, boolean isAuthor) {
        List<ArticleVo> articleVoList = new ArrayList<>();
        for (Article record : records) {
            articleVoList.add(copy(record, isTag, isAuthor,false,false));
        }
        return articleVoList;
    }
    private List<ArticleVo> copyList(List<Article> records, boolean isTag, boolean isAuthor,boolean isBody, boolean isCategory) {
        List<ArticleVo> articleVoList = new ArrayList<>();
        for (Article record : records) {
            articleVoList.add(copy(record, isTag, isAuthor,isBody,isCategory));
        }
        return articleVoList;
    }

    @Autowired
    private CategoryService categoryService;

    //数据库中的List<Article>转换为List<ArticleVo>,因为前端Vue的data格式是ArticleVo。
    private ArticleVo copy(Article article, boolean isTag, boolean isAuthor, boolean isBody, boolean isCategory) {
        ArticleVo articleVo = new ArticleVo();
        BeanUtils.copyProperties(article, articleVo); //将相同的属性copy到articleVo中
        //但是注意Article实体类的createDate 是Long类型，而ArticleVo的是String类型，copy不过来。所以要转换格式。
        articleVo.setCreateDate(new DateTime(article.getCreateDate()).toString("yyyy-MM-dd HH:mm"));

        //思考：并不是所有的接口 都需要标签 和 作者信息
        if (isTag) {
            Long articleId = article.getId(); //将实体类【Article】的对象【article】赋值给articleId
            articleVo.setTags(tagService.findTagsByArticleId(articleId));
        }
        if (isAuthor) {
            Long authorId = article.getAuthorId();
            articleVo.setAuthor(sysUserService.findUserById(authorId).getNickname());
        }
        if (isBody) {
            Long bodyId = article.getBodyId();
            articleVo.setBody(findArticleBodyById(bodyId));
        }
        if (isCategory) {
            Long categoryId = article.getCategoryId();
            articleVo.setCategory(categoryService.findCategoryById(categoryId));
        }
        return articleVo;
    }

    @Autowired
    ArticleBodyMapper articleBodyMapper;

    private ArticleBodyVo findArticleBodyById(Long bodyId) {
        ArticleBody articleBody = articleBodyMapper.selectById(bodyId);//从ms_article_body 查询出了文章
        ArticleBodyVo articleBodyVo = new ArticleBodyVo();
        articleBodyVo.setContent(articleBody.getContent());
        return articleBodyVo;
    }
}

